package com.sk.weichat.view;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sk.weichat.R;
import com.sk.weichat.bean.VerifyNicknameBean;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.util.RegexUtils;
import com.sk.weichat.util.StringUtils;
import com.sk.weichat.util.ToastUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;

/**
 * 注册 完善信息 昵称存在时 昵称选择对话框
 */
public class NicknameDialog extends Dialog {

    private CoreManager mCoreManager;
    private NameOnClickListener nameOnClickListener;
    private ConfirmBtnOnClickListener confirmBtnOnClickListener;
    private EditText etNickname;
    private List<TextView> listNameTvs = new ArrayList<>();
    private String[] strings;
    private Button btnConfirm;
    private Context mContext;
    private String oldName;
    private TextView tvTitle, tvTips;
    private ImageView ivClear;
    private TextView tvNickNameMarked;

    public NicknameDialog(Context context, CoreManager coreManager) {
        super(context, R.style.BottomDialog);
        mContext = context;
        mCoreManager=coreManager;
    }

    public void setNameOnClickListener(String oldName, String[] strings, NameOnClickListener nameOnClickListener) {
        this.strings = strings;
        this.nameOnClickListener = nameOnClickListener;
        this.oldName = oldName;
    }

    public void setConfirmBtnOnClickListener(ConfirmBtnOnClickListener confirmBtnOnClickListener) {
        this.confirmBtnOnClickListener = confirmBtnOnClickListener;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_nickname_select);
        getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        etNickname = findViewById(R.id.et_nickname_dialog);
        tvNickNameMarked= findViewById(R.id.tv_nickname_marked_dialog);
        btnConfirm = findViewById(R.id.btn_nickname_confirm);
        tvTitle = findViewById(R.id.tv_nickname_dialog_title);
        tvTips = findViewById(R.id.tv_nickname_tips);
        ivClear = findViewById(R.id.iv_clear_name_dialog);
        btnConfirm = findViewById(R.id.btn_nickname_confirm);
        listNameTvs.add(findViewById(R.id.tv_nickname_one));
        listNameTvs.add(findViewById(R.id.tv_nickname_two));
        listNameTvs.add(findViewById(R.id.tv_nickname_three));
        listNameTvs.add(findViewById(R.id.tv_nickname_four));
        if (!TextUtils.isEmpty(oldName)) {
            ivClear.setVisibility(View.VISIBLE);
            etNickname.setText(oldName);
            etNickname.setSelection(oldName.length());
        }
        initEvent();
        editTextLimit();
    }

    private void initEvent() {
        showNameUsed(strings);
        //可选昵称点击事件
        for (int i = 0; i < listNameTvs.size(); i++) {
            TextView tv = listNameTvs.get(i);
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (nameOnClickListener != null) {
                        String nickname = tv.getText().toString();
                        if (!TextUtils.isEmpty(nickname)) {
                            tv.setTextColor(mContext.getResources().getColor(R.color.text_purple));
                            tv.setBackgroundResource(R.drawable.bg_border_purple_circle);
                            nameOnClickListener.getName(tv.getText().toString());
                            countDownTimer.start();
                        }
                    }
                }
            });
        }
        //确认按钮点击事件
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (confirmBtnOnClickListener != null) {
                    String nickname = etNickname.getText().toString();
                    if (TextUtils.isEmpty(nickname)) {
                        etNickname.setError(StringUtils.editTextHtmlErrorTip(mContext, R.string.name_empty_error));
                    } else if (nickname.length() < 2 || nickname.length() > 6) {
                        etNickname.setError(StringUtils.editTextHtmlErrorTip(mContext, "请输入2-6位昵称"));
                    } else {
                        checkNickname();
                    }
                }
            }
        });
        findViewById(R.id.iv_nickname_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        ivClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etNickname.setText("");
            }
        });
    }

    //倒计时，用于显示推荐昵称被点击时的背景
    CountDownTimer countDownTimer = new CountDownTimer(250, 50) {
        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            dismiss();
        }
    };

    //显示确定按钮
    private void showBtn() {
        for (int i = 0; i < listNameTvs.size(); i++) {
            listNameTvs.get(i).setVisibility(View.GONE);
        }

        tvTitle.setVisibility(View.GONE);
        tvTips.setVisibility(View.GONE);
        btnConfirm.setVisibility(View.VISIBLE);
    }

    //名字被占用时显示的布局
    private void showNameUsed(String[] names) {
        btnConfirm.setVisibility(View.GONE);
        tvTitle.setVisibility(View.VISIBLE);
        tvTips.setVisibility(View.VISIBLE);
        if (names != null && names.length == 4) {
            for (int i = 0; i < names.length; i++) {
                listNameTvs.get(i).setVisibility(View.VISIBLE);
                listNameTvs.get(i).setText(names[i]);
            }
        } else {
            showBtn();
        }
    }

    //限制EditText输入特殊符号
    private void editTextLimit() {
        InputFilter filter_space = new InputFilter() {//空格过滤
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(" "))
                    return "";
                else
                    return null;
            }
        };
        InputFilter filter_speChat = new InputFilter() {//特殊字符过滤
            @Override
            public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
                String speChat = "[^a-zA-Z0-9\\u4e00-\\u9fa5]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(charSequence.toString());
                if (matcher.find()) return "";
                else return null;
            }
        };
        etNickname.setFilters(new InputFilter[]{filter_space, filter_speChat, new InputFilter.LengthFilter(6)});
        etNickname.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {//清空输入框时显示确认按钮
                    showBtn();
                    ivClear.setVisibility(View.GONE);
                    btnConfirm.setBackgroundResource(R.drawable.bg_round_black30);
                    tvNickNameMarked.setTextColor(ContextCompat.getColor(mContext,R.color.hint_text_color));
                    tvNickNameMarked.setText(mContext.getString(R.string.nickname_market_first));
                    return;
                }
                showBtn();
                ivClear.setVisibility(View.VISIBLE);
                editNumChange(s);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    private void editNumChange(CharSequence s) {
        if(s.length() == 1){//昵称长度2-6位之间
            tvNickNameMarked.setText(mContext.getString(R.string.nickname_num_error));
            tvNickNameMarked.setTextColor(ContextCompat.getColor(mContext,R.color.color_red));
        }else if (s.length() > 1) {

            if (RegexUtils.checkDigit(s.toString())) {
                tvNickNameMarked.setText(mContext.getString(R.string.nickname_market_second));
                tvNickNameMarked.setTextColor(ContextCompat.getColor(mContext,R.color.color_red));
            } else {
                btnConfirm.setBackgroundResource(R.drawable.bg_round_purple);
                tvNickNameMarked.setText(mContext.getString(R.string.nickname_market_first));
                tvNickNameMarked.setTextColor(ContextCompat.getColor(mContext,R.color.hint_text_color));
            }

        } else {
            btnConfirm.setBackgroundResource(R.drawable.bg_round_black30);
            tvNickNameMarked.setTextColor(ContextCompat.getColor(mContext,R.color.hint_text_color));
            tvNickNameMarked.setText(mContext.getString(R.string.nickname_market_first));
        }
    }

    //校验昵称是否被使用
    private void checkNickname() {
        String nickname = etNickname.getText().toString();
        if (TextUtils.isEmpty(nickname)) {
            ToastUtil.showToast(mContext, mContext.getString(R.string.name_empty_error));
            tvNickNameMarked.setText(mContext.getString(R.string.nickname_market_second));
            tvNickNameMarked.setTextColor(ContextCompat.getColor(mContext,R.color.color_red));
            return;
        }

        if (nickname.length() < 2 || nickname.length() > 6) {
            ToastUtil.showToast(mContext, "请输入2-6位昵称");
            return;
        }
        //判读纯数据
        if (RegexUtils.checkDigit(nickname)) {
            ToastUtil.showToast(mContext, mContext.getString(R.string.nickname_market_second));
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("nickName", nickname);
        DialogHelper.showMessageProgressDialog(mContext, "正在校验名称...");
        HttpUtils.get().url(mCoreManager.getConfig().CHECK_NICKNAME)
                .params(params)
                .build()
                .execute(new BaseCallback<VerifyNicknameBean>(VerifyNicknameBean.class) {

                    @Override
                    public void onResponse(ObjectResult<VerifyNicknameBean> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result == null) {
                            DialogHelper.dismissProgressDialog();
                            ToastUtil.showErrorData(mContext);
                            return;
                        }
                        if (result.getResultCode() == 1) {
                            confirmBtnOnClickListener.getName(nickname);
                            dismiss();
                        } else if (result.getResultCode() == com.xuan.xuanhttplibrary.okhttp.result.Result.CODE_NICKNAME_USED) {//昵称被占用
                            if (result.getData() != null) {
                                showNameUsed(result.getData().getNickNames());
                            }
                        }else if(result.getResultCode() == Result.CODE_NICKNAME_ILLEGAL){//昵称非法
                            ToastUtil.showToast(mContext, result.getResultMsg());
                            etNickname.setText("");
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    public void setCurrentName(String currentName) {
        this.oldName = currentName;
    }

    public interface NameOnClickListener {
        void getName(String name);
    }

    public interface ConfirmBtnOnClickListener {
        void getName(String name);
    }

}
